package com.tmall.testgen.server.infocollect;

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tmall.testgen.common.bo.interact.apply.ApplyConnection;
import com.tmall.testgen.common.bo.interact.back.InterceptInfo;
import com.tmall.testgen.common.util.StringUtil;
import com.tmall.testgen.server.socket.SocketServer;

/**
 * @author haojia
 * @date 2014-07-04
 */
public class DataCenter {
	
	
	public static boolean isStart=false;
	/**
	 * 用户信息
	 */
	private static Map<String,UserData> userDatas=new HashMap<String,UserData>();
	

	/**
	 * 已经加载的类和方法
	 */
	private static Map<String,List<String>> loadedClassAndMethods=new HashMap<String,List<String>>();
	
	
	
	public static void addLoadedClassAndMethods(String className,String methodDes){
		if(loadedClassAndMethods.get(className)==null){
			loadedClassAndMethods.put(className, new ArrayList<String>());
		}
		if(methodDes==null){
			return;
		}
		//System.out.println("加入"+className+",  "+methodDes);
		loadedClassAndMethods.get(className).add(methodDes);
		for(String userId:userDatas.keySet()){
			UserData userData=userDatas.get(userId);
			//System.out.println("匹配："+userDatas.get(userId).getInterceptDes()+","+className);
			//haojia:getMaxDataVersion( ):int
			boolean isMatchIntercept=StringUtil.isMatchClass(userDatas.get(userId).getInterceptDes(), className)
			                        &&StringUtil.isMatchMethod(userDatas.get(userId).getInterceptDes(), methodDes);
			
			if(isMatchIntercept){
				userData.addLoadedInterceptClassAndMethods(className, methodDes);
			}
			
			boolean isMatchMock=StringUtil.isMatchClass(userDatas.get(userId).getMockDes(), className)
                    &&StringUtil.isMatchMethod(userDatas.get(userId).getMockDes(), methodDes);
			
			if(isMatchMock){
				userData.addLoadedMockClassAndMethods(className, methodDes);
			}
		}
	}
	
	/**
	 * 重新刷新以保证
	 */
	public static void refresh(){
		for(String clazz: loadedClassAndMethods.keySet()){
			List<String> methods=loadedClassAndMethods.get(clazz);
			
			for(String userId:userDatas.keySet()){
				UserData userData=userDatas.get(userId);
				
				if(StringUtil.isMatchClass(userDatas.get(userId).getInterceptDes(), clazz)){
					if(!userData.isLoadedInterceptClassAndMethods(clazz)){
						for(String method:methods){
						    if(StringUtil.isMatchMethod(userDatas.get(userId).getInterceptDes(), method))
						        userData.addLoadedInterceptClassAndMethods(clazz, method);
						}
						
					}
				}
				if(StringUtil.isMatchClass(userDatas.get(userId).getMockDes(), clazz)){
					if(!userData.isLoadedMockClassAndMethods(clazz)){
						for(String method:methods){
						    if(StringUtil.isMatchMethod(userDatas.get(userId).getMockDes(), method))
						        userData.addLoadedMockClassAndMethods(clazz, method);
						}
						
					}
				}
			}
		}
		
	}
	public static boolean isClassLoaded(String className){
		return loadedClassAndMethods.get(className)!=null;
	}
	public static void addUserOutPutStream(String userId,OutputStream outStream ){
		getUserDataFillIfNull(userId).setOutPutStream(outStream);
	}
	
	public static void removeUser(String userId){
		userDatas.remove(userId);
		if(userDatas.size()==0){
			System.out.println("关闭socket");
			SocketServer.stop();
		}
	}
	public static void addApplyConnection(ApplyConnection apply){
		//System.out.println("加入信息中心配置:int"+apply.getInterceptDes()+" mock:"+apply.getMockDes());
		UserData userData=getUserDataFillIfNull(apply.getUserId());
		userData.setInterceptDes(apply.getInterceptDes());
		userData.setMockDes(apply.getMockDes());
	}
	
	
	private static InterceptInfo getNewInterceptInfo(InterceptInfo info){
		InterceptInfo n=new InterceptInfo();
		n.setClassName(info.getClassName());
		n.setClassSimpleName(info.getClassSimpleName());
		n.setException(info.getException());
		n.setMethodName(info.getMethodName());
		n.setParamNames(info.getParamNames());
		n.setMethodParamContent(info.getMethodParamContent());
		n.setParams(info.getParams());
		n.setResult(info.getResult());
		n.setBeanName(info.getBeanName());
		n.setExecuteTime(info.getExecuteTime());
		return n;
	}
	
	
	public static void addIntercept(InterceptInfo info){
		//1、匹配所有用户的拦截url，如果匹配加入到对应的 List中
		//2、刷给用户客户端
		for(String userId:userDatas.keySet()){
			UserData userData=userDatas.get(userId);
			
			boolean isMatchIntercept=StringUtil.isMatchClass(userData.getInterceptDes(), info.getClassName())
                    &&StringUtil.isMatchMethod(userData.getInterceptDes(), info.getMethodName()+info.getMethodParamContent());


			//处理拦截信息
			if(isMatchIntercept){
				InterceptInfo n=getNewInterceptInfo(info);
				n.setType(InterceptInfo.TYPE_INTERCEPT);
				userData.addUserInfo(info);
			}
			
			// System.out.println("mockdes:"+userData.getMockDes()+",info.getClassName()"+info.getClassName()+","+info.getMethodName()+info.getMethodParamContent());
	         
			 boolean isMatchMock=StringUtil.isMatchClass(userData.getMockDes(), info.getClassName())
	                &&StringUtil.isMatchMethod(userData.getMockDes(), info.getMethodName()+info.getMethodParamContent());

			//System.out.println(info.getClassName()+"mock匹配"+isMatchMock);
			
			//处理mock信息
			if(isMatchMock){
				InterceptInfo n=getNewInterceptInfo(info);
				n.setType(InterceptInfo.TYPE_MOCK);
				userData.addUserInfo(n);
			}
		}
	}
	
	
	private static UserData getUserDataFillIfNull(String userId){
		if(userDatas.get(userId)==null){
			 UserData userData=new UserData();
			 userData.setUserId(userId);
			userDatas.put(userId, userData);
		}
		return userDatas.get(userId);
	}

	public static Map<String, UserData> getUserDatas() {
		return userDatas;
	}
	
	
	
	
	
	
}
